﻿// -----------------------------------------------------------------------
// <copyright file="HandleNullModelAttribute.cs" company="EPAM Systems">
////Copyright (c) EPAM Systems, 2012. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace MBOP.Website.CustomAttributes
{
	#region Usings

	using System;
	using System.Reflection;
	using System.Web.Mvc;

	#endregion

	/// <summary>
	/// Represents the handle null model attribute.
	/// </summary>
	public class HandleNullModelAttribute : ActionFilterAttribute
	{
		/// <summary>
		/// Called the ASP MVC before the result executes.
		/// </summary>
		/// <param name="filterContext">The result executing context.</param>
		public override void OnResultExecuting(ResultExecutingContext filterContext)
		{
			Type resultType = filterContext.Result.GetType();

			if (resultType == typeof(ViewResult) || resultType == typeof(PartialViewResult))
			{
				PropertyInfo propertyInfo = resultType.GetProperty("Model");

				object model = propertyInfo.GetValue(filterContext.Result, null);

				if (model == null)
				{
					filterContext.Cancel = true;
					filterContext.Result = new HttpNotFoundResult();
					filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
				}
			}
		}
	}
}